<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" :value="isAllChecked" @change="changedFn" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格/元</th>
          <th>数量</th>
          <th>总价/元</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="personList.length">
        <tr
          is="PersonListTr"
          v-for="(item, index) in personList"
          :key="index"
          :obj="item"
          :index="index"
          :sum="sumPrice(index)"
          @subObj="delFFn"
        ></tr>
      </tbody>
      <tfoot v-if="personList.length">
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ total }}</td>
        </tr>
      </tfoot>
      <tfoot v-else>
        <tr>
          <td colspan="6">没有数据了哦~</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import PersonListTr from "./components/PersonListTr.vue";
export default {
  components: {
    PersonListTr,
  },
  data() {
    return {
      personList: [
        {
          name: "Yu",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "Sam",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "J",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "S",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    sumPrice(i) {
      return this.personList[i].price * this.personList[i].num;
    },
    delFFn(i) {
      this.personList.splice(i, 1);
    },
    changedFn(e) {
      this.personList.forEach((obj) => {
        obj.checked = e.target.checked;
      });
    },
  },
  computed: {
    // 报错：Computed property "isAllChecked" was assigned to but it has no setter.
    //vue某次更新以后计算属性需要设置set get 方法|| v-model 改成 :value就不会报错
    isAllChecked() {
      return this.personList.every((obj) => obj.checked);
    },
    /*  isAllChecked: {
      get() {
        return this.personList.every((obj) => obj.checked);
      },
      set() {},
    }, */
    total() {
      let newPL = this.personList.filter((obj) => obj.checked == true);
      //console.log(newPL);
      //console.log(newPL.reduce((acc, obj) => acc + obj.num * obj.price, 0));
      return newPL.reduce((acc, obj) => acc + obj.num * obj.price, 0);
    },
  },
};
</script>

<style></style>
